from rest_framework import serializers
from apps.users.models import User
from django.contrib.auth.models import Group


class AdminSerializer(serializers.ModelSerializer):
    class Meta:
        model = User
        fields = '__all__'
        extra_kwargs = {
            'password': {
                'write_only': True
            }
        }

    def create(self, validated_data):
        # 这里没有用 **validated_data  因为这里调用的是父类的create方法，传字典过去，父类自己解包
        admin = super().create(validated_data)
        # 密码加密 把is_staff 设置成管理员身份
        password = validated_data['password']
        admin.set_password(password)
        admin.is_staff = True
        admin.save()
        return admin

    def update(self, instance, validated_data):
        # 调用父类的方法去更新数据
        super().update(instance, validated_data)
        # 密码是 write_only，不会显示回去前端，
        # 如果密码重新输入有值就说明更改了密码
        # 我们还要进行密码加密
        password = validated_data['password']
        if password is not None:
            instance.set_password(password)
            instance.save()
        return instance


class GroupSerializer(serializers.ModelSerializer):
    class Meta:
        model = Group
        fields = '__all__'
